
package me.zhengjie.rest;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.base.AjaxResult;
import me.zhengjie.domain.AppEvent;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.UserDto;
import me.zhengjie.service.AppEventCateService;
import me.zhengjie.service.AppEventService;
import me.zhengjie.service.dto.*;
import me.zhengjie.utils.SecurityUtils;
import me.zhengjie.utils.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
* @website https://el-admin.vip
* @author IQW
* @date 2022-07-03
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "事件上报管理")
@RequestMapping("/api/event")
public class ApiEventController {

    private final AppEventService appEventService;
    private final AppEventCateService appEventCateService;
    private final UserService appUserService;

    @GetMapping(value = "/index")
    @ApiOperation("巡护事件分类")
    public AjaxResult index(AppEventCateQueryCriteria criteria){

        criteria.setCateIdNo(1);
        return   AjaxResult.success(appEventCateService.queryAllApi(criteria));
    }

    /**
     *
     * @param workId 关联任务
     * @param type 类型：1事件处理（状态0，1），2事件记录日志（状态2）
     * @param criteria
     * @param pageable
     * @return
     */
    @GetMapping(value = "/list")
    @ApiOperation("事件记录列表")
    public AjaxResult queryAppWork(@RequestParam(defaultValue = "0") int workId,
                                   @RequestParam(defaultValue = "0") int type,
                                   @RequestParam(defaultValue = "") String startTime,
                                   @RequestParam(defaultValue = "") String endTime,
                                   AppEventQueryCriteria criteria,
                                   @PageableDefault(sort = {"eventId"}, direction = Sort.Direction.DESC) Pageable pageable){

        return AjaxResult.success(appEventService.queryAllApiPage(workId,type,startTime,endTime,pageable));

      /*
        return   AjaxResult.success(appEventService.queryAllApi(criteria,pageable));
      */
    }

    @GetMapping(value = "/detail")
    @ApiOperation("巡护事件详情")
    public AjaxResult detail(@RequestParam Integer eventId){

        AppEventDto appEventDto = appEventService.findById(eventId);
        if(null == appEventDto){
            return AjaxResult.error("巡护事件不存在");
        }
        UserDto user1 = appUserService.findById(appEventDto.getUserId());
        if(null == user1){
            return AjaxResult.error("关联用户数据不存在");
        }
        Map<String, Object> rets = new HashMap<>();
        rets.put("status",appEventDto.getStatus());
        rets.put("nickName",user1.getNickName());
        rets.put("workNo",user1.getWorkNo());

        rets.put("addTime",appEventDto.getAddTime());
        rets.put("title",appEventDto.getTitle());
        rets.put("note",appEventDto.getNote());
        rets.put("imgs",appEventDto.getImgs());
        rets.put("voice",appEventDto.getVoice());
        rets.put("vtime",appEventDto.getVtime());
        rets.put("address",appEventDto.getAddress());
        rets.put("lon",appEventDto.getLon());
        rets.put("lat",appEventDto.getLat());

        //查询回复
        Map<String, Object> rMap = new HashMap<>();
        if(appEventDto.getActWay() == 1){

            UserDto user2 = appUserService.findById(appEventDto.getToUserId());
            if (null == user2) {
                return AjaxResult.error("关联用户数据不存在");
            }

            rMap.put("nickName", user2.getNickName());
            rMap.put("workNo", user2.getWorkNo());

            rMap.put("addTime", appEventDto.getUpdateTime());
            rMap.put("actWay", 1);
            rMap.put("note", "无需处理");
            rMap.put("imgs", "");
            rMap.put("voice", "");
            rMap.put("vtime", 0);

            rets.put("reply", rMap);

        }else if(appEventDto.getActWay() == 2){
            AppEventDto reply = appEventService.findByFId(appEventDto.getEventId());
            if (null != reply) {
                UserDto user2 = appUserService.findById(reply.getUserId());
                if (null == user2) {
                    return AjaxResult.error("关联用户数据不存在");
                }

                rMap.put("nickName", user2.getNickName());
                rMap.put("workNo", user2.getWorkNo());
                rMap.put("actWay", 2);
                rMap.put("addTime", reply.getAddTime());
                rMap.put("note", reply.getNote());
                rMap.put("imgs", reply.getImgs());
                rMap.put("voice", reply.getVoice());
                rMap.put("vtime", reply.getVtime());

                rets.put("reply", rMap);

            }
        }else {
            rets.put("reply", null);
        }

        return AjaxResult.success(rets);

    }

    @PostMapping(value = "/add")
    @ApiOperation("新增事件上报")
    public AjaxResult add(@Validated @RequestBody AppEvent resources){

        if(resources.getLat() == 0||resources.getLon() == 0|| StringUtils.isEmpty(resources.getAddress())){
            return AjaxResult.error("位置参数错误");
        }
        if(StringUtils.isEmpty(resources.getNote())&&StringUtils.isEmpty(resources.getImgs())&&StringUtils.isEmpty(resources.getVoice())){
            return AjaxResult.error("内容参数错误");
        }
        if(resources.getType() == 0){
            return AjaxResult.error("类型参数错误");
        }

        AppEventCateDto cate = appEventCateService.findById(resources.getType());
        if(null == cate){
            return AjaxResult.error("事件分类错误");
        }
        resources.setCateId(resources.getType());
        resources.setCate(cate.getTitle());
        resources.setTitle(cate.getTitle());
        resources.setIcon(cate.getImg());
        if(cate.getType() == 1){
            resources.setType(1);   //普通事件
        }else if(cate.getType() == 2){
            resources.setType(3);   //紧急事件
        }

        resources.setUserId(SecurityUtils.getCurrentUserId().intValue());

        resources.setFid(0);
        resources.setToUserId2(0);
        resources.setToUserId3(0);
        resources.setActWay(0);
        resources.setStatus(0);
        appEventService.create(resources);
        return AjaxResult.success("上报成功");
    }


    @PostMapping(value = "/reply")
    @ApiOperation("事件处理（回复）")
    public AjaxResult reply(@Validated @RequestBody AppEvent resources){

        appEventService.reply(resources,SecurityUtils.getCurrentUserId().intValue());

        return AjaxResult.success("处理成功");
    }

}